package cn.bitkit.tools.data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * 
 * 	金额计算,请尽量用分为单位计算,避免精度问题
 * @author changbo
 *
 */
public class AmountUtil {
	
	public static final BigDecimal PERCENTAGE = new BigDecimal(100);

	public static BigDecimal yuanToFen(BigDecimal yuan){
		if(yuan == null) {
			return BigDecimal.ZERO;
		}
		return yuan.multiply(PERCENTAGE);
	}
	
	public static BigDecimal fenToYuan(BigDecimal fen){
		if(fen == null) {
			return BigDecimal.ZERO;
		}
		return fen.divide(PERCENTAGE, 2, RoundingMode.HALF_UP);
	}
	
	public static BigDecimal formatAmount(BigDecimal amt){
		if(amt == null) {
			return BigDecimal.ZERO;
		}
		return amt.setScale(2, RoundingMode.HALF_UP);
	}
	
	public static BigDecimal scaleFair(BigDecimal amt){
		if(amt == null) {
			return BigDecimal.ZERO;
		}
		//4舍6入，5看下一位的值
		if(amt.multiply(new BigDecimal(1000)).longValue()%10 == 5) {
			//奇进偶舍
			if(amt.multiply(new BigDecimal(10000)).longValue()%2 == 1) {
				return amt.setScale(2, RoundingMode.HALF_UP);
			}else {
				return amt.setScale(2, RoundingMode.HALF_DOWN);
			}
		}else {
			return amt.setScale(2, RoundingMode.HALF_UP);
		}
	}

	public static String format(BigDecimal yuan){
		if(yuan == null) {
			return "";
		}
		DecimalFormat format = new DecimalFormat("#,###.00##");
		return format.format(yuan);
	}
	
}
